<template>
  <div class="threshold-management">
    <h2>阈值管理</h2>
    <!-- <el-button type="primary" @click="openAddDialog">添加标准</el-button> -->
    <!-- <el-button type="success" @click="syncThresholdsToInventory" style="margin-left: 10px;">同步标准到库存</el-button> -->

    <el-table :data="thresholds" border style="width: 100%">
      <el-table-column prop="id" label="ID (库存项ID)" width="120" align="center" />
      <el-table-column prop="thresholdName" label="商品名称 (阈值名称)" width="200" align="center" />
      <el-table-column prop="defaultValue" label="预警触发数量 (标准阈值)" width="200" align="center" />
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" @click="openEditDialog(scope.row)">修改阈值</el-button>
          <!-- <el-button type="danger" @click="deleteThreshold(scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="修改商品预警触发数量" width="400px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="form.thresholdName" disabled />
        </el-form-item>
        <el-form-item label="预警触发数量">
          <el-input-number v-model="form.defaultValue" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveThreshold">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 创建阈值管理专用的API客户端实例
const thresholdApiClient = axios.create({
  baseURL: 'http://192.168.140.19:8001',
  timeout: 10000
});

const thresholds = ref([]);
const dialogVisible = ref(false);
// const dialogType = ref('add'); // Dialog is always 'edit' now
const form = ref({ id: null, thresholdName: '', defaultValue: 0 });

// 获取阈值列表 (现在是获取库存项及其预警数量)
const fetchThresholds = async () => {
  try {
    const response = await thresholdApiClient.post('/api/threshold-definitions/list', {});
    if (response.data && Array.isArray(response.data)) {
      thresholds.value = response.data;
    } else {
      thresholds.value = [];
      console.warn('获取到的阈值数据格式不正确或为空:', response.data);
    }
  } catch (error) {
    console.error('获取阈值列表失败:', error);
    ElMessage.error('获取阈值列表失败，请检查网络或联系管理员。');
    thresholds.value = [];
  }
};

// 打开编辑对话框
const openEditDialog = (row) => {
  // dialogType.value = 'edit'; // Not needed anymore
  form.value = { ...row }; // form now holds ItemSpecificThresholdDto data
  dialogVisible.value = true;
};

// 保存阈值 (实际上是更新库存项的 alertTriggerQuantity)
const saveThreshold = async () => {
  const url = '/api/threshold-definitions/update'; // Always update
  const payload = { ...form.value }; // Payload is ItemSpecificThresholdDto: {id, thresholdName, defaultValue}

  try {
    await thresholdApiClient.post(url, payload);
    ElMessage.success('更新成功');
    dialogVisible.value = false;
    fetchThresholds(); // Refresh list
  } catch (error) {
    console.error('保存阈值失败:', error);
    const errorMsg = error.response && error.response.data && (typeof error.response.data === 'string' ? error.response.data : error.response.data.message)
                     ? (typeof error.response.data === 'string' ? error.response.data : error.response.data.message)
                     : '更新失败，请检查提交的数据和网络。';
    ElMessage.error(errorMsg);
  }
};

/*
// 打开添加对话框 - REMOVED
const openAddDialog = () => {
  dialogType.value = 'add';
  form.value = { id: null, thresholdName: '', defaultValue: 0 }; 
  dialogVisible.value = true;
};
*/

/*
// 删除阈值 - REMOVED
const deleteThreshold = async (id) => {
  try {
    await post('/api/threshold-definitions/delete', { id });
    ElMessage.success('删除成功');
    fetchThresholds(); // Refresh list
  } catch (error) {
    console.error('删除阈值失败:', error);
    const errorMsg = error.response && error.response.data && (typeof error.response.data === 'string' ? error.response.data : error.response.data.message) 
                     ? (typeof error.response.data === 'string' ? error.response.data : error.response.data.message) 
                     : '删除失败，请检查网络或联系管理员。';
    ElMessage.error(errorMsg);
  }
};
*/

onMounted(() => {
  fetchThresholds();
});

/*
// 同步阈值到库存功能 - REMOVED
const syncThresholdsToInventory = async () => {
  try {
    const res = await post('/api/inventory/sync-alert-triggers', {});
    if (res) { 
      ElMessage.success('阈值已成功同步到库存记录！');
    } else {
      ElMessage.error('同步失败，请检查后端服务。');
    }
  } catch (error) {
    console.error('同步阈值失败:', error);
    ElMessage.error('同步阈值操作失败。');
  }
};
*/
</script>

<style scoped>
.threshold-management {
  padding: 20px;
}
</style>